package servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import beans.Account;
import beans.DateDeserializer;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import dao.AccountDAO;

/**
 * Servlet implementation class ManagerServlet
 */
@WebServlet("/accountmanager")
public class ManagerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	private void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		String cmd = request.getParameter("cmd");

		if (cmd != null) {
			switch (cmd) {
			case "del":
				String[] array = request.getParameterValues("json[]");

				// System.out.println(Arrays.toString(array));
				boolean result = true;
				for (String id : array) {
					if (!AccountDAO.deleteById(id)) {
						result = false;
					}
				}
				response.getWriter().write("Kết quả xóa: " + result);
				break;
			case "sav":
				String json = request.getParameter("json");
				JsonElement ele = new JsonParser().parse(json);
				Iterator<JsonElement> list = ele.getAsJsonArray().iterator();
				ArrayList<Account> accounts = new ArrayList<>();
				Gson gson = new GsonBuilder().registerTypeAdapter(Date.class,
						new DateDeserializer()).create();
				while (list.hasNext()) {
					accounts.add(gson.fromJson(list.next(), Account.class));
				}
				for (Account account : accounts) {
					boolean rs = AccountDAO.update(account);
					System.out.println(rs + " " + account);
				}
				break;
			}
		} else {
			List<Account> list = AccountDAO.selectAll();

			request.setAttribute("accountList", list);
			request.getRequestDispatcher("AccountManager.jsp").forward(request,
					response);
		}
	}

}
